package com.wits.qso.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件工具类
 * @author       chenkaile
 * @createTime   2013-2-19
 */
public class FileUtils {
	/**
	 * 删除指定目录下的所有文件
	 * @param folderPath 目录路径
	 * @return true:删除成功 false:删除失败
	 */
	public static boolean delAllFile(String folderPath) {
		boolean flag = false;
		File file = new File(folderPath);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (folderPath.endsWith(File.separator)) {
				temp = new File(folderPath + tempList[i]);
			} else {
				temp = new File(folderPath + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(folderPath + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(folderPath + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 删除指定文件
	 * @param filePath 指定文件的路径
	 * @return true:删除成功 false:删除失败
	 */
	public static boolean delFile(String filePath) {
		boolean flag = false;
		File file = new File(filePath);
		if (!file.exists()) {
			return flag;
		}
		flag = (new File(filePath)).delete();
		return flag;
	}

	/**
	 * 删除指定文件夹(包括文件夹下的所有文件)
	 * @param folderPath 指定文件夹路径
	 * @return true:删除成功 false:删除失败
	 */
	public static boolean delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
 	/**
 	 * 读取文本文件的内容
 	 * @param curfile   文本文件路径
 	 * @return 返回文件内容
 	 */
 	public static String readFile(String curfile)
 	{
			File f = new File(curfile);
		    try
		    {
	 		  if (!f.exists()) throw new Exception();
	 		  FileReader cf=new FileReader(curfile);
			  BufferedReader is = new BufferedReader(cf);
			  String filecontent = ""; 			  
			  String str = is.readLine();
			  while (str != null){
			  	filecontent += str;
		    	str = is.readLine();
		    	if (str != null)
		    		filecontent += "\n";
			  }
			  is.close();
			  cf.close();
			  return filecontent;
		    }
		    catch (Exception e)
		    {
		      System.err.println("不能读属性文件: "+curfile+" \n"+e.getMessage());
		      return "";
		    }
 		
 	}
	/**
	 * 取指定文件的扩展名
	 * @param filePathName  文件路径
	 * @return 扩展名
	 */
	public static String getFileExt(String filePathName)
	{
	    int pos = 0;
	    pos = filePathName.lastIndexOf('.');
	    if(pos != -1)
	        return filePathName.substring(pos + 1, filePathName.length());
	    else
	        return "";
		
	}
	
	/**
	 * 读取文件大小
	 * @param filename 指定文件路径
	 * @return 文件大小
	 */
	public static int getFileSize(String filename)
	{
		try
		{
			File fl = new File(filename);
			int length = (int)fl.length();
			return length;
	  	} 
	  	catch (Exception e)
	  	{
	  		return 0;
	  	}
		
	}
	
	/**
	 * 拷贝文件到指定目录
	 * @param srcPath 源文件路径
	 * @param destPath 目标文件路径
	 * @return true:拷贝成功 false:拷贝失败
	 */
	public static boolean copyFile(String srcPath,String destPath){
		try
		{
			File fl = new File(srcPath);
			int length = (int)fl.length();
		  	FileInputStream is = new FileInputStream(srcPath);
		  	FileOutputStream os = new FileOutputStream(destPath);
			byte[] b = new byte[length];
		  	is.read(b);
		  	os.write(b);
		  	is.close();
		  	os.close();
		  	return true;
	  	} 
	  	catch (Exception e)
	  	{
	  		return false;
	  	}
	}
	
	/**
	 * 
	 *方法摘要：文件剪切
	 *@param source  源文件路径
	 *@param dest    目标文件夹
	 *@return boolean
	 */
	public static boolean cut(String source,String dest){
		File sourceFile = new File(source);
		File destFile = new File(dest);
		return sourceFile.renameTo(destFile);
	}
	
	/**
	 * 通过正则获取文件名
	 */
	public static String getFileName(String filePath){
		String regEx = "";
		if(filePath.indexOf("\\") == -1){
			regEx = ".+\\/(.+)$"; 
		}
		else{
			regEx = ".+\\\\(.+)$"; 
		}
        Pattern p=Pattern.compile(regEx); 
        Matcher m=p.matcher(filePath);
        String fileName = "";
        if(m.find()){
        	fileName = m.group(1);
        }
        return fileName;
	}
	
	/**
	 * 通过正则获取文件后缀名
	 * @param fileName 文件名(不包含路径)
	 */
	public static String getFileExtendion(String fileName){
		String regEx="^(.+)\\..+";
        Pattern p=Pattern.compile(regEx); 
        Matcher m=p.matcher(fileName); 
        String extendtion = "";
        if(m.find()){
        	extendtion = m.group(1);
        }
        return extendtion;
	}
	
	/**
	 * 
	 *方法摘要：文件下载
	 *@param  downLoadPath  待下载文件路径
	 *@param  os            输出流
	 *@return boolean
	 */
	public static boolean downloadFile(String downLoadPath,OutputStream os){  
		boolean isSuccess = false;
		BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  
		try {
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(os);  
			byte[] buff = new byte[20480];
			int bytesRead = 0;  
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
	            bos.write(buff, 0, bytesRead);  
	        }  
	        bis.close();  
	        bos.close();
	        isSuccess = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}    
        return isSuccess;
	}
	
	/**
	 * 
	 *方法摘要：文件下载
	 *@param  downLoadPath  待下载文件路径
	 *@param  writer        写入流
	 *@return boolean
	 */
	public static boolean downloadFile(String downLoadPath,PrintWriter writer){
		boolean isSuccess = false;
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(downLoadPath));
			String line = null;
			while((line = reader.readLine())!= null){
				writer.write(line, 0, line.length());
			}
			writer.flush();
			isSuccess = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				writer.close();
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return isSuccess;
	}
	
	/**
	 * 根据文件得到该文件中文本内容的编码
	 * 
	 * @param file 要分析的文件
	 */
	public static Charset getCharset(File file) {
	        String charset = "GBK"; // 默认编码
	        byte[] first3Bytes = new byte[3];
	        try {
	            boolean checked = false;
	            BufferedInputStream bis = new BufferedInputStream(
	                  new FileInputStream(file));
	            bis.mark(0);
	            int read = bis.read(first3Bytes, 0, 3);
	            if (read == -1){
	                return Charset.forName(charset);
	            }
	            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
	                charset = "UTF-16LE";
	                checked = true;
	            } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1]
	                == (byte) 0xFF) {
	                charset = "UTF-16BE";
	                checked = true;
	            } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1]
	                    == (byte) 0xBB
	                    && first3Bytes[2] == (byte) 0xBF) {
	                charset = "UTF-8";
	                checked = true;
	            }
	            bis.reset();
	            if (!checked) {
	                int loc = 0;
	                while ((read = bis.read()) != -1) {
	                    loc++;
	                    if (read >= 0xF0)
	                        break;
	                    //单独出现BF以下的，也算是GBK
	                    if (0x80 <= read && read <= 0xBF)
	                        break;
	                    if (0xC0 <= read && read <= 0xDF) {
	                        read = bis.read();
	                        if (0x80 <= read && read <= 0xBF)// 双字节 (0xC0 - 0xDF)
	                            // (0x80 -
	                            // 0xBF),也可能在GB编码内
	                            continue;
	                        else
	                            break;
	                     // 也有可能出错，但是几率较小
	                    } else if (0xE0 <= read && read <= 0xEF) {
	                        read = bis.read();
	                        if (0x80 <= read && read <= 0xBF) {
	                            read = bis.read();
	                            if (0x80 <= read && read <= 0xBF) {
	                                charset = "UTF-8";
	                                break;
	                            } else
	                                break;
	                        } else
	                            break;
	                    }
	                }
	            }
	            bis.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        //System.out.println(charset);
	        return Charset.forName(charset);
	}
}
